/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.appspot.android2gather;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.signature.SignatureMethod;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.appspot.android2gather.configuration.ServerConfiguration;
import com.appspot.android2gather.util.QueryHelper;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.google.buzz.Buzz;

/**
 * 
 * Main activity, Application entry point.. Displays the home screen and creates
 * the menu.
 * 
 * @author Christoph 'Gigi' Fuchs
 * 
 */
public class LetsDoStuff extends Activity {

	/** The button create. */
	private Button buttonCreate;

	/** The is logged in. */
	public static boolean isLoggedIn = false;

	public static String BUZZ_OAUTH_TOKEN = "";

	public static String BUZZ_VERIFIYER = "";

	private Button buttonFindLocal;

	private Button buttonMyActivites;

	public static Activity letsDoStuff;

	private Button quit;

	private Button buttonBuzzLogon;
	
	private static Bundle FBBundle;
	
	public static  Bundle getFBBundle()
	{
		//
		return (Bundle) FBBundle.clone();
		
	}

	private Button mButtonFacebookLogon;
	public static Buzz buzz;
	public static Facebook facebook = new Facebook(
			ServerConfiguration.FACEBOOK_APP_ID);

	/**
	 * Called when the activity is first created.
	 * 
	 * @param savedInstanceState
	 *            the saved instance state
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		// display logged in status
		isLoggedIn = QueryHelper.isLoggedIn(getApplicationContext());
		Context context = getApplicationContext();
		CharSequence text = "Logged in: " + isLoggedIn;
		int duration = Toast.LENGTH_LONG;
		Toast toast = Toast.makeText(context, text, duration);
		toast.show();

		buttonCreate = (Button) findViewById(R.id.button_createActivity);
		buttonFindLocal = (Button) findViewById(R.id.button_findLocalActivities);
		letsDoStuff = this;

		SessionStore.restore(facebook, this);

		/**
		 * only for debugging purposes
		 */
		// isLoggedIn=true;

		if (!isLoggedIn) {
			Intent WebViewIntent = new Intent(getApplicationContext(),
					LogonWebView.class);
			startActivity(WebViewIntent);
		}

		// Create two separate onClickListeners here rather than forwarding the
		// user in the create activity view if he is not logged in, since the
		// user would be able to navigate back to the 'create activity' page
		// using the back button
		if (isLoggedIn) {
			// Switch to create activity view if the user is logged in already
			buttonCreate.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.i("View", "Switching to create activity view");
					Intent createActivityIntent = new Intent(v.getContext(),
							CreateActivity.class);
					startActivity(createActivityIntent);
				}
			});
		} else {
			// Not logged in, switch to log in
			buttonCreate.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.i("View",
							"User is not logged in - switching to login view");
					Intent loginIntent = new Intent(v.getContext(),
							LogonWebView.class);
					startActivity(loginIntent);
				}
			});
		}

		buttonFindLocal.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i("View",
						"Switching to find local activities view (search results)");
				Intent findLocalIntent = new Intent(v.getContext(),
						ActivitiesInSurrounding.class);
				startActivity(findLocalIntent);
				// startActivity(new Intent(v.getContext(),
				// FacebookLogin.class));
			}
		});

		buttonMyActivites = (Button) findViewById(R.id.button_my_activities);

		buttonMyActivites.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i("View", "Switching to MyActivities (search results)");
				startActivity(new Intent(v.getContext(), MyActivities.class));

			}
		});

		buttonBuzzLogon = (Button) findViewById(R.id.button_buzz_logon);

		buttonBuzzLogon.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				buzz = new Buzz();
				String authUri;
				try {
					consumer = new DefaultOAuthConsumer(
							"android2gather.appspot.com",
							"k0J+3q9FdBPxJWn++NjsTy7U",
							SignatureMethod.HMAC_SHA1);

					String scope = Buzz.BUZZ_SCOPE_WRITE;
					provider = new DefaultOAuthProvider(
							consumer,
							"https://www.google.com/accounts/OAuthGetRequestToken?scope="
									+ URLEncoder.encode(scope, "utf-8"),
							"https://www.google.com/accounts/OAuthGetAccessToken",
							"https://www.google.com/buzz/api/auth/OAuthAuthorizeToken?scope="
									+ URLEncoder.encode(scope, "utf-8")
									+ "&hd=default&domain="
									+ URLEncoder.encode(
											"android2gather.appspot.com",
											"utf-8"));

					Log.i("Oauth", "Fetching request token...");

					authUrl = provider.retrieveRequestToken(OAuth.OUT_OF_BAND);

					Log.i("Oauth", "Request token: " + consumer.getToken());
					Log.i("Oauth", "Token secret: " + consumer.getTokenSecret());

					Log.i("Oauth", "Now visit:\n" + authUrl
							+ "\n... and grant this app authorization");

					Intent buzzIntent = new Intent(v.getContext(),
							BuzzLogonWebView.class);

					buzzIntent.putExtra("buzzurl", authUrl);
					startActivity(buzzIntent);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					Log.e("Buzz", QueryHelper.getStrackTrace(e));
				}

			}

		});

		mButtonFacebookLogon = (Button) findViewById(R.id.button_facebook_logon);

		mButtonFacebookLogon.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				try {
//					//LetsDoStuff.facebook.logout(LetsDoStuff.letsDoStuff);
//				} catch (Exception e1) {
//					Log.e("Facebook Logout", QueryHelper.getStrackTrace(e1));
//				}
				LetsDoStuff.facebook.authorize(LetsDoStuff.letsDoStuff,
						ServerConfiguration.permissions, new DialogListener() {
							@Override
							public void onComplete(Bundle values) {
								Toast.makeText(getApplicationContext(), "Successfully authorized on Facebook", Toast.LENGTH_SHORT);
								FBBundle = values;
							}

							@Override
							public void onFacebookError(FacebookError e) {
								Toast.makeText(getApplicationContext(), "Authorization ERROR"+e.getMessage(), Toast.LENGTH_SHORT);

							}

							@Override
							public void onError(DialogError e) {
								Toast.makeText(getApplicationContext(), "Dialog ERROR:"+e.getMessage(), Toast.LENGTH_SHORT);

							}

							@Override
							public void onCancel() {
								// TODO Auto-generated method stub

							}
						}

				);
			}
		});

	}

	public static OAuthConsumer consumer;

	public static OAuthProvider provider;

	public static String authUrl;

	public static List<String> getFound(String contents, String regex) {
		if (isEmpty(regex) || isEmpty(contents)) {
			return null;
		}
		List<String> results = new Vector<String>();
		Pattern pattern = Pattern.compile(regex, Pattern.UNICODE_CASE);
		Matcher matcher = pattern.matcher(contents);

		while (matcher.find()) {
			if (matcher.groupCount() > 0) {
				results.add(matcher.group(1));
			} else {
				results.add(matcher.group());
			}
		}
		return results;
	}

	public static boolean isEmpty(String str) {
		if (str != null && str.trim().length() > 0) {
			return false;
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.quit:
			finish();
			return true;
		}

		return false;
	}

}